<template>
  <div class="mapDiv">
    <div id="tmap" ref="mapContainer"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

const mapContainer = ref(null)
const TDT_KEY = '4e0627d28549df303d6bf150fecc543f'

onMounted(() => {
  // 动态加载天地图API
  const script = document.createElement('script')
  script.src = `https://api.tianditu.gov.cn/api?v=4.0&tk=${TDT_KEY}`
  document.head.appendChild(script)
  script.onload = initMap
})

function initMap() {
  // 初始化地图
  var map = new T.Map(mapContainer.value)

  // 设置地图中心点和缩放级别
  map.centerAndZoom(new T.LngLat(104.061755, 30.572806), 10)
  map.addControl(new T.Control.Zoom())
  map.addControl(new T.Control.Scale())
  map.setStyle('black')

  // 关键修改：等待地图加载完成
  map.onload = function () {
    console.log('天地图底图加载完成')

    // 添加矢量底图
    const vecLayer = new T.TileLayer('vec', {
      minZoom: 3,
      maxZoom: 18
    })
    map.addLayer(vecLayer)

  }
}

</script>

<style scoped>
.mapDiv {
  display: flex;
  width: 100%;
  height: 100%;
  background-image: url('@/assets/uiResources/map-panel.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  justify-content: center;
  align-items: center;
}

#tmap {
  width: 96%;
  height: 95%;
}
</style>